const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 分页列校级通知
router.get("/list", async function (req, res, next) {
  const where = {};
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const title = req.query.title;
  const sticky = req.query.sticky;
  if (title) {
    where.title = {
      [Op.like]: "%" + title + "%",
    };
  }
  if (sticky) {
    where.sticky = {
      [Op.like]: sticky == true ? 1 : 0,
    };
  }
  const result = await models.notification.findAndCountAll({
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
    order:[["sticky", "desc"]]
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 新增校级通知
router.post("/", async function (req, res, next) {
  models.notification.create({
    title: req.body.title,
    content: req.body.content,
    sticky: 0,
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 修改校级通知
router.put("/", async function (req, res, next) {
  const result = await models.notification.findByPk(req.body.id);
  result.update(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 删除校级通知
router.delete("/:id", async function (req, res, next) {
  models.notification.findByPk(req.params.id).then(res => {
    res.destroy(req.body);
  })

  res.json({
    code: 200,
    msg: "操作成功",
  });
});
module.exports = router;
